package com.liuceng.zen.web.controller;

import com.liuceng.zen.common.Result;
import com.liuceng.zen.common.utils.Encodes;
import com.liuceng.zen.constants.Constants;
import com.liuceng.zen.pojo.domain.Member;
import com.liuceng.zen.pojo.domain.WechatUser;
import com.liuceng.zen.pojo.form.ModifyPasswordForm;
import com.liuceng.zen.pojo.form.ProfileForm;
import com.liuceng.zen.service.AccountService;
import com.liuceng.zen.service.ImageService;
import com.liuceng.zen.service.MemberService;
import com.liuceng.zen.service.WechatBindService;
import com.liuceng.zen.web.auth.realm.ShiroDbRealm.UserContext;
import com.liuceng.zen.web.auth.utils.AuthUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


/**
 * 帐号相关功能
 *
 * @author liyuhang
 */
@Controller
@RequestMapping(value = "/profile")
public class ProfileController extends BaseController {
  private final static Logger LOG = LoggerFactory.getLogger(CommonController.class);
  @Value("${appid}")
  private String appid;
  @Value("${wechat.redirect.url}")
  private String redirectUrl;
  @Autowired
  private AccountService accountService;
  @Autowired
  private MemberService memberService;
  @Autowired
  ImageService imageService;
  @Autowired
  WechatBindService wechatBindService;

  /**
   * 账号信息
   * 
   * @return
   */
  @RequestMapping(value = "", method = RequestMethod.GET)
  public String profile(@ModelAttribute("form") ProfileForm profileForm,BindingResult result,
      HttpServletRequest request) {
    List<WechatUser> wechatUsers = wechatBindService.getBindedWechat(getCurrentUserId());
    profileForm.setWechatUsers(wechatUsers);
    request.setAttribute("appid",appid);
    request.setAttribute("redirectUrl",redirectUrl);
    return "profile";
  }

  /**
   * 账号信息修改
   * 
   * @param redirectAttributes
   * @return
   */
  @RequestMapping(value = "", method = RequestMethod.POST)
  public String doUpdateAccount(@ModelAttribute("form") ProfileForm profileForm,
      BindingResult result, RedirectAttributes redirectAttributes, HttpServletRequest req) {
    if (result.hasErrors()) {
      return profile(profileForm, result, req);
    }

    profileForm.setCurrentUserId(getCurrentUserId());
    Result relt = memberService.updateAcManage(profileForm);

    if (relt.getErrors() != null && relt.getErrors().hasErrors()) {
      result.addAllErrors(relt.getErrors());
      return profile(profileForm, result, req);
    }

    // 向userContext中塞入image的path路径
    Member member = memberService.findMember(getCurrentUserId());

    UserContext userContext = getUserContext();
    userContext.setMember(member);
    req.getSession().setAttribute("member", member);

    redirectAttributes.addFlashAttribute(Constants.OK_MSG, "账号信息修改成功");
    return "redirect:/profile";
  }

  // 进入修改密码页面
  @RequestMapping(value = "/modify_password", method = RequestMethod.GET)
  public String modifyPassword(@ModelAttribute("form") ModifyPasswordForm form,
      BindingResult result) {
    return "account/modify_password";
  }

  // 修改密码
  @RequestMapping(value = "/modify_password", method = RequestMethod.POST)
  public String doModifyPassword(@ModelAttribute("form") ModifyPasswordForm form,
      BindingResult result, RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
      return modifyPassword(form, result);
    }
    form.setCurrentUserId(getCurrentUserId());
    Result relt = memberService.updatePassword(form);
    //
    if (relt.getErrors() != null && relt.getErrors().hasErrors()) {
      result.addAllErrors(relt.getErrors());
      return modifyPassword(form, result);
    }

    redirectAttributes.addFlashAttribute(Constants.OK_MSG, "登录密码修改成功");
    return "redirect:/profile/modify_password";
  }


  @RequestMapping(value = "/checkout_password", method = RequestMethod.GET)
  public void username(HttpServletRequest request, HttpServletResponse response,
      String oldPassword) {
    UserContext userContext = getUserContext();
    Member member = userContext.getMember();
    String hashedPassword =
        AuthUtils.encryptPlainPassword(oldPassword, Encodes.decodeHex(member.getSalt()));
    // 判断密码是否正确，不正确输出"true"
    if (!hashedPassword.equals(member.getPassword())) {
      try {
        PrintWriter out = response.getWriter();
        out.write("true");
        out.flush();
        out.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        LOG.error(e.getMessage(), e);
        if (LOG.isDebugEnabled()) {
          LOG.debug("检查原始密码是否正确验证失败");
        }
      }
    }
  }

  @RequestMapping(value = "/remove/binding", method = RequestMethod.POST)
  @ResponseBody
  public Integer removeBinding(Integer wechatId) {
      return wechatBindService.removeBinding(wechatId);
  }

}
